package com.css.fxfzysx.modules.cztDataMange.repository.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzysx.modules.cztDataMange.entity.RdInformationEntity;
import com.css.fxfzysx.modules.cztDataMange.repository.DomeFacilitiesRepository;
import com.css.fxfzysx.modules.vaomeFacilities.entity.CztMajorProjectsEntity;
import com.css.fxfzysx.util.PlatformDateUtils;
import com.css.fxfzysx.util.PlatformObjectUtils;
import com.css.fxfzysx.util.PlatformSessionUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@Repository
public class DomeFacilitiesRepositoryImpl implements DomeFacilitiesRepository {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Override
    public Boolean saveRdInformation(RdInformationEntity rd) {
        String sql = "insert into czt_reservior(cr_id, cr_name, location, longitude, latitude, capacity, year, dam_length, dam_height, top_width, " +
                "structure_type, type, intensity, site, space, filling, dam_foundation, maintenance_status, create_user, create_time, update_user, " +
                "update_time, del_flag, extends1, extends2, extends3, extends4, extends5, extends6,  extends7, extends8, extends9, extends10, " +
                "attach_id, province, city, county, geom, upload_time,version_id) " +
                "values(:crId, :crName, :location, :longitude, :latitude, :capacity, :year, :damLength, :damHeight, " +
                ":topWidth, :structureType, :type, :intensity, :site, :space, :filling, :damFoundation, :maintenanceStatus, :createUser, " +
                ":createTime, :updateUser, :updateTime, :delFlag, :extends1, :extends2, :extends3, :extends4, :extends5, :extends6, " +
                ":extends7, :extends8, :extends9, :extends10, " +
                ":attachId, :province, :city, :county, ST_GeometryFromText(:geom,4490), :uploadTime,:versionId)";
        SqlParameterSource source = new BeanPropertySqlParameterSource(rd);
        return namedParameterJdbcTemplate.update(sql, source) > 0;
    }

    @Override
    public int getReserviorDataByProvince(String province) {
        try {
            String sql = "select count(cr_id) from czt_reservior where del_flag= '0' and province= ?";
            int count = jdbcTemplate.queryForObject(sql, Integer.class, province);
            return count;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public int getMajorProjectDataByProvince(String province) {
        try {
            String sql = "select count(cmp_id) from czt_major_project where del_flag= '0' and province= ? ";
            int count = jdbcTemplate.queryForObject(sql, Integer.class, province);
            return count;
        } catch (Exception e) {
            return 0;
        }
    }

    @Override
    public String getCode() {
        try {
            StringBuilder sql = new StringBuilder("select code from czt_major_projects where del_flag = '0' order by create_time desc limit 1");
            return jdbcTemplate.queryForObject(sql.toString(), String.class);
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public void save(CztMajorProjectsEntity entity) {
        jdbcTemplate.update("insert into czt_major_projects  (id,seism_name,seism_date,seism_time,magnitude,project_type,longitude,latitude,fortification,year,destructive6_state,destructive7_state,destructive8_state,destructive9_state,destructive10_state,destructive11_state,destructive12_state,create_user,create_user_name,create_time,del_flag,version_id,code,geom)" +
                " values ('" + entity.getId() + "', '" + entity.getSeismName() + "', '" + entity.getSeismDate() + "', '" + entity.getSeismTime() + "', '" + entity.getMagnitude() + "', '" + entity.getProjectType() + "', '" + entity.getLongitude() + "', '" + entity.getLatitude() + "', '" + entity.getFortification() + "', '" + entity.getYear() + "', '" + entity.getDestructive6State() + "', '" + entity.getDestructive7State() + "', '" + entity.getDestructive8State() + "', '" + entity.getDestructive9State() + "', '" + entity.getDestructive10State() + "', '" + entity.getDestructive11State() + "', '" + entity.getDestructive12State() + "', '" + entity.getCreateUser() + "', '" + entity.getCreateUserName() + "', '" + entity.getCreateTime() + "', '" + entity.getDelFlag() + "', '" + entity.getVersionId() + "', '" + entity.getCode() + "',st_geomfromtext('POINT('||" + entity.getLongitude() + "||' '|| " + entity.getLatitude() + "||')',4490))");
    }

    @Override
    public HashMap<String, Object> getByRegionAndType(Integer type, String province, String city, String county, Integer page, Integer size) {
        StringBuilder sql = new StringBuilder();
        HashMap<String, Object> resultMap = new HashMap();
        if (type == 1) {
            sql.append("select * from czt_major_projects where del_flag = '0' ");
        } else {
            sql.append("select * from czt_reservior where del_flag = '0' ");
        }
        if (PlatformObjectUtils.isNotEmpty(province)) {
            sql.append(" and province = '" + province + "'");
        }
        if (PlatformObjectUtils.isNotEmpty(city)) {
            sql.append(" and city = '" + city + "'");
        }
        if (PlatformObjectUtils.isNotEmpty(county)) {
            sql.append(" and county = '" + county + "'");
        }
        if (type == 1) {
            Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(CztMajorProjectsEntity.class)).size();
            StringBuilder limitSql = new StringBuilder(" limit " + size + " offset " + (page - 1) * size);
            sql.append(limitSql);
            List<CztMajorProjectsEntity> data = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(CztMajorProjectsEntity.class));
            resultMap.put("total", total);
            resultMap.put("rows", data);
        } else {
            Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(RdInformationEntity.class)).size();
            StringBuilder limitSql = new StringBuilder(" limit " + size + " offset " + (page - 1) * size);
            sql.append(limitSql);
            List<RdInformationEntity> data = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(RdInformationEntity.class));
            resultMap.put("total", total);
            resultMap.put("rows", data);
        }
        return resultMap;
    }

    @Override
    public void updateByTypeAndId(Integer key, Object value) {
        if(key == 1){
            CztMajorProjectsEntity entity = JSONObject.parseObject(JSONObject.toJSONString(value), CztMajorProjectsEntity.class);
            entity.setUpdateUser(PlatformSessionUtils.getUserId());
            entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
            jdbcTemplate.update("UPDATE  czt_major_projects  SET seism_name=?,seism_date=?,seism_time=?,magnitude=?,project_type=?,year=?,destructive6_state=?,destructive7_state=?,destructive8_state=?,destructive9_state=?,destructive10_state=?,destructive11_state=?,destructive12_state=?,update_user=?,update_time=?"
                            +" where id=?",
                    entity.getSeismName(),entity.getSeismDate(),entity.getSeismTime(),entity.getMagnitude(),entity.getProjectType(),entity.getYear(),entity.getDestructive6State(),entity.getDestructive7State(),entity.getDestructive8State(),entity.getDestructive9State(),entity.getDestructive10State(),entity.getDestructive11State(),entity.getDestructive12State(),entity.getUpdateUser(),entity.getUpdateTime(),
                    entity.getId()
            );
        }else {
            RdInformationEntity entity = JSONObject.parseObject(JSONObject.toJSONString(value), RdInformationEntity.class);
            entity.setUpdateUser(PlatformSessionUtils.getUserId());
            entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
            jdbcTemplate.update("UPDATE  czt_reservior  SET cr_name=?,location=?,longitude=?,latitude=?,capacity=?,year=?,dam_length=?,dam_height=?,top_width=?,structure_type=?,type=?,intensity=?,site=?,space=?,filling=?,dam_foundation=?,maintenance_status=?,update_user=?,update_time=?,extends1=?,extends2=?,extends3=?,extends4=?,extends5=?,extends6=?,extends7=?,extends8=?,extends9=?,extends10=?,attach_id=?,province=?,city=?,county=?,upload_time=?"
                            +" where cr_id=?",
                    entity.getCrName(),entity.getLocation(),entity.getLongitude(),entity.getLatitude(),entity.getCapacity(),entity.getYear(),entity.getDamLength(),entity.getDamHeight(),entity.getTopWidth(),entity.getStructureType(),entity.getType(),entity.getIntensity(),entity.getSite(),entity.getSpace(),entity.getFilling(),entity.getDamFoundation(),entity.getMaintenanceStatus(),entity.getUpdateUser(),entity.getUpdateTime(),entity.getExtends1(),entity.getExtends2(),entity.getExtends3(),entity.getExtends4(),entity.getExtends5(),entity.getExtends6(),entity.getExtends7(),entity.getExtends8(),entity.getExtends9(),entity.getExtends10(),entity.getAttachId(),entity.getProvince(),entity.getCity(),entity.getCounty(),entity.getUploadTime(),
                    entity.getCrId()
            );
        }
    }
}
